// map.js
import { handleRepairStatus } from '../../../utils/repair'
import qmapsdk from '../../../utils/qqmap'
import Dialog from '@vant/weapp/dialog/dialog';
Page({
  data: {
    latitude: 40.060539,
    longitude: 116.343847,
    points: [],
    markers: []
  },
  // 调接口 获取起点 终点 经纬度，当前是写死的  from: '40.227978,116.22998',  to: '40.22077,116.23128',
  onLoad() {
    this.getDetail()  // 详情接口数据
    this.getPolyline() // 路线规划
  },
  // 获取详情
  async getDetail() {
    const res = await wx.http({
      url: `/repair/${this.options.id}`
    })
    handleRepairStatus(res)
    this.setData(res)
  },
  getPolyline() {
    qmapsdk.direction({
      mode: 'bicycling',//可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
      //from参数不填默认当前地址
      from: '40.227978,116.22998',
      to: '40.22077,116.23128',
      success: (res) => {
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        let kr = 1000000;
        const coors = res.result.routes[0].polyline
        for (let i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        //将解压后的坐标放入点串数组points中
        let points = []
        for (let i = 0; i < coors.length; i += 2) {
          points.push({ latitude: coors[i], longitude: coors[i + 1] })
        }
        //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
        this.setData({
          latitude: points[70].latitude,
          longitude: points[70].longitude,
          polyline: [{
            points,
            color: '#FF0000DD',
            width: 4
          }],
          markers: [
            {
              id: 1,
              latitude: points[70].latitude,
              longitude: points[70].longitude,
              iconPath: '/static/images/marker.png',
              width: 40,
              height: 40,
            },
            {
              id: 2,
              latitude: 40.22077,
              longitude: 116.23128,
              width: 32,
              height: 30,
            },
          ],
        })
      }
    })
  },
  toUpdate() {
    wx.navigateTo({
      url: '/repair_pkg/pages/form/index?id=' + this.options.id,
    })
  },
  cancelRepair() {
    Dialog.confirm({
      title: '提示',
      message: '确定取消报修吗？',
    }).then(async () => {
      await wx.http({
        url: `/cancel/repaire/${this.options.id}`,
        method: 'PUT'
      })
      wx.showToast({
        title: '取消成功',
      })
      // 重新刷新页面
      this.onLoad()
    }).catch(() => {
        // on cancel
      });
  }
})

